function $(sel) {
    return document.querySelector(sel);
}
function $a(sel) {
    return document.querySelectorAll(sel);
}

function render(arr) {
    $('.valid').innerHTML = '';
    $('.invalid').innerHTML = '';
    let valitStr = '';
    let invalitStr = '';
    arr.forEach((v, i) => {
        if (v.status) {
            valitStr += `
            <tr>
                <td>${v.id}</td>
                <td>${v.name}</td>
                <td>${v.activity}</td>
                <td>
                    <button class="red"  data-id="${v.id}">剔除</button>
                </td>
            </tr>
            `;
        } else {
            invalitStr += `
            <tr>
                <td>${v.id}</td>
                <td>${v.name}</td>
                <td>${v.activity}</td>
                <td>${v.comment}</td>
            </tr>
            `;
        }
    });
    $('.valid').innerHTML = valitStr;
    $('.invalid').innerHTML = invalitStr;
    $a('.valid button').forEach((v, i) => {
        v.addEventListener('click', async function (e) {
            await fetch(`/api/${e.target.dataset.id}`, {
                method: 'DELETE',
            });
            let res = await fetch('/api/query/all');
            let data = await res.json();
            render(data.data);
        });
    });
}

async function init() {
    let res = await fetch('/api/query/all');
    let data = await res.json();
    render(data.data);

    res = await fetch('/api/amount');
    data = await res.json();
    $('#count').value = data;
}

$('#btnSearch').addEventListener('click', async function () {
    let id = $('#stdid').value.trim();
    if (id == '') {
        id = 'all';
    }
    let res = await fetch(`/api/query/${id}`);
    let data = await res.json();
    if(!data.success){
        alert('未找到');
        return;
    }
    render(data.data);
});

$('#btnModify').addEventListener('click', async function () {
    if ($('#count').disabled) {
        $('#count').disabled = false;
        $('#btnModify').innerText = '保存';
    } else {
        await fetch(`/api/modifyamount/${$('#count').value.trim()}`)
        $('#count').disabled = true;
        $('#btnModify').innerText = '修改';
    }
});

init();
